import Flutter
import Foundation

class TextBoxWindows: NSObject {
    public var stackView = UIStackView()
    var textViews: [UITextView] = []

    public var num: Int

    init(_ args: [String: Any?]) {
        num = args["num"] as! Int
        let fontSize = args["fontSize"] as! Int
        super.init()
        stackView.axis = .vertical
        stackView.alignment = .fill
        stackView.distribution = .fillEqually
        stackView.spacing = 1
        for _ in 1 ... num {
            let textView = UITextView()
            textView.font = UIFont.systemFont(ofSize: CGFloat(fontSize))
            textView.isUserInteractionEnabled = false
            textView.backgroundColor = .black
            textView.textColor = .white
            textViews.append(textView)
            let uiView = UIView()
            uiView.addSubview(textView)
            stackView.addArrangedSubview(uiView)
            textView.snp.makeConstraints { make in
                make.edges.equalToSuperview().inset(UIEdgeInsets(top: 10, left: 10, bottom: 5, right: 5))
            }
        }
    }

    public func handle(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) -> Bool {
        switch call.method {
            case "updateTextBoxText":
                updateText(call.arguments as! [String])
                result(true)
                return true
            default:
                break
        }
        return false
    }

    public func updateText(_ texts: [String]) {
        textViews.forEach { textView in
            let i = textViews.firstIndex(of: textView)
            if i != nil, i! < texts.count {
                let newText = texts[i!]
                if newText != textView.text {
                    textView.text = newText
                    textView.scrollRangeToVisible(NSMakeRange(textView.text.count, 1))
                    textView.layoutManager.allowsNonContiguousLayout = false
                }
            }
        }
    }

    public func close() {
        textViews.removeAll()
        stackView.removeFromSuperview()
    }
}
